/*
场景控制，模拟客户端

*/
layui.define(['form', 'cosjs', 'scene', 'storage'], function(exports) {
    let $ = layui.jquery,
        form = layui.form,
        cosjs = layui.cosjs,
        scene = layui.scene;
    let _data_record = null;

    function quick(data) {
        console.log(data);
        _data_record = data;
        this.sdk = data.sdk;
        return {
            quick: data.role
        };
    }
    quick.finish = function finish(data) {
        form.on('submit(quick-new)', function(data) {
            scene.show('gzone/login', _data_record.sdk);
            return false;
        });
        form.on('submit(quick-submit)', function(data) {
            let _index = parseInt(data.field.quick);
            let _role_record = _data_record.role[_index];
            quick.submit(_role_record);
            return false;
        })
    }
    quick.submit = function submit(_role_record) {

        let opts = _role_record.opts;
        scene.gamesdk = gsdk(opts, cosjs.ajax);
        scene.gamesdk.gzone.login(_role_record.zoneLoginData).then(ret => {
            let task = scene.gamesdk.gzone.initialize();
            task.on("begin", (k) => {
                let opt = scene.gamesdk.gzone.modules[k];
                console.log(`gzone initialize ${opt.name} begin`);
            })
            task.on("result", (k, err, ret) => {
                let opt = scene.gamesdk.gzone.modules[k];
                console.log(`gzone initialize ${opt.name} finish`, err, ret);
            })
            return task.start();
        }).then(() => {
            return scene.gamesdk.gzone.select(_role_record.zoneSelectData);
        }).then(() => {
            return scene.gamesdk.game.login();
        }).then(roles => {
            return scene.gamesdk.game.select(_role_record.gameSelectData);
        }).then(() => {
            let modules = scene.gamesdk.game.modules;
            //预加载游戏模块
            let task = scene.gamesdk.game.initialize();
            task.interval = 1000;
            task.on("begin", (k) => {
                let opt = modules[k];
                // $('#progress-title').html(`${opt.name}`)
                console.log(`game initialize ${opt.name} begin`);
            })
            task.on("result", (k, err, ret) => {
               // progress.add(1);
                let opt = modules[k];
                console.log(`game initialize ${opt.name} finish`, err, ret);
            })
            return task.start();
        }).then(() => {
            scene.show('game/main');
            return false;
        }).catch(err => {
            cosjs.alert(err);
            return false;
        });
    }
    exports('gzone/quick', quick);
})